import pandas as pd
from django.shortcuts import render
from .forms import UploadFileForm
import json
from django.http import JsonResponse
import os
from django.conf import settings


def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            # 保存上传的文件
            uploaded_file = request.FILES['file']
            file_path = os.path.join(settings.MEDIA_ROOT, 'uploads', uploaded_file.name)
            print(f'file_path:{file_path}')
            # 在写入文件部分添加目录创建和异常处理
            try:
                os.makedirs(os.path.dirname(file_path), exist_ok=True)
                with open(file_path, 'wb+') as destination:
                    for chunk in uploaded_file.chunks():
                        destination.write(chunk)
            except Exception as e:
                # 记录错误日志或返回提示
                print(f"文件写入失败: {e}")
                return render(request, 'data_analysis/error.html', {'message': '文件写入失败，请检查路径和权限'})

            # 读取数据
            df = pd.read_csv(file_path)

            # 获取数据基本信息
            columns = list(df.columns)
            print(f'columns:{columns}')
            data_info = {
                'shape': df.shape,
                'columns': columns,
                'head': df.head().to_dict(orient='records')
            }
            print(f'data_info:{data_info}')
            # 保存列名供后续使用
            request.session['uploaded_file_path'] = file_path
            request.session['columns'] = columns

            return render(request, 'data_analysis/preview.html', {
                'data_info': data_info,
                'form': UploadFileForm()
            })
    else:
        form = UploadFileForm()
    return render(request, 'data_analysis/upload.html', {'form': form})


def generate_chart(request):
    if request.method == 'POST':
        file_path = request.session.get('uploaded_file_path')
        x_column = request.POST.get('x_column')
        y_column = request.POST.get('y_column')

        if not file_path or not x_column or not y_column:
            return JsonResponse({'error': '缺少必要参数'}, status=400)

        try:
            df = pd.read_csv(file_path)

            # 提取绘图数据
            x_data = df[x_column].tolist()
            y_data = df[y_column].tolist()

            # 准备ECharts数据
            chart_data = {
                'xAxis': {
                    'type': 'category',
                    'data': x_data
                },
                'yAxis': {
                    'type': 'value'
                },
                'series': [{
                    'data': y_data,
                    'type': 'line',
                    'smooth': True
                }]
            }

            return JsonResponse(chart_data)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    return JsonResponse({'error': '无效请求'}, status=400)    